package com.superlz.demo.security.browser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;


/**
 * 1.实现UserDetailsService接口，并重写对应方法
 *
 * lz： 处理用户信息获取逻辑：UserDetailsService接口
 *      处理用户校验逻辑：UserDetails接口
 *      处理密码加密解密：PasswordEncoder接口
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 用户信息的获取：加载用户名、密码和权限到secutity框架中，供其与前端请求的校验
     *
     * lz：实际会从数据库中加载
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("登录用户名：" + username);
        // 1.获取用户信息：根据用户名查找用户信息

        // 2.处理用户校验逻辑（是否可用，是否过期，是否锁定）：根据查找到的用户信息判断用户是否被冻结等：true

        String password = passwordEncoder.encode("123456");
        // 每次加密的密码都不一样
        logger.info("数据库密码是：" + password);
        return new User(username, password,
                true, true, true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
